import { F2EConfig, createServer, logger } from 'f2e-server3'
import { NativeTemplatedApp } from 'f2e-server3/lib/server-engine/native/app'
import { STFEase } from './index'
import * as os from 'os'

const { argv } = process
const mode = process.env['F2E_MODE'] || argv[argv.length - 1]
const port = Number(process.env['PORT']) || 7100
const ease = new STFEase({
    /**
     * windows 环境下可以配置环境变量启动 ADB_SHELL=adb.exe
     */
    adb: process.env['ADB_SHELL'] || (os.platform() === 'win32' ? 'adb.exe' : 'adb'),
    /**
     * 要和f2e-server的端口一致
     */
    port,
    /**
     * adb forward 起始端口，会自动检查是否占用，已占用则 +1
     */
    port_tcp_start: Number(process.env['PORT_FORWARD_BEGIN']) || 7400,
    /**
     * 默认展示宽度
     */
    screen_width: Number(process.env['SCREEN_WIDTH']) || 360,
    /**
     * 是否默认安装需要的apk文件
    */
    install_pkg: process.env['INSTALL_PKG'] === 'true',
    /**
     * 帧率限制
     */
    rate: Number(process.env['RATE']) || 50,
})


const config: F2EConfig = {
    mode: mode === 'dev' || mode === 'build' ? mode : 'prod',
    port,
    try_files: [
        "index.html"
    ],
    namehash: {
        entries: ["index\.html$"],
        searchValue: [
            `import.*? from "(.*?)";`
        ],
        replacer: (output, hash) => `${output}?${hash}`
    },
    watchFilter: (p) => /^(index|src|favicon|$)/.test(p),
    buildFilter: (p) => /^(index|favicon|$)/.test(p),
    middlewares: [
        ease.create_route,
    ],
    onServerCreate: (app) => {
        const _app = app as NativeTemplatedApp
        if (mode != 'build') {
            ease.create_server(_app.server)
        }
    },
    dest: 'stf-ease-server',
}

createServer(config)